#include "include.h"

#if DEVICE_MIX_AUX_EN
/*
 * 文件名称: mic_mix_aux.c
 * 功能描述: 本文件用于配置双通道（MIC + MIC 或者MIC + AUX）立体声数据转单声道数据发送

 ****************************************************************************************
    code :
    buf  : 10000*2 Bytes
    time : 160M 下 120 个点处理 147us
 */
static sdadc_cfg_t mic_mix_auxcfg = {CH_MICL0,  (12 << 6),   SPR_48000,    ADC2DAC_EN,    128,    NULL};
extern bool sdadc_w4_kick;
static pcm_callback_t mic_mix_aux_output_callback;

AT(.text.bsp.wireless_mic_mix_aux)
void mic_mix_aux_init(u8 sample_rate, u16 samples)
{
    mic_mix_auxcfg.sample_rate = sample_rate;
    mic_mix_auxcfg.samples = samples*2;
    mic_channel_get_param(&mic_mix_auxcfg.channel, &mic_mix_auxcfg.gain);

    if( mic_mix_auxcfg.channel == CH_MICR0){
//        mic_mix_auxcfg.channel |= CH_MICL0;
        mic_mix_auxcfg.channel |= CH_AUXL_PB1;
    }else{
        mic_mix_auxcfg.channel |= CH_MICR0;
    }
    //软件数字增益
    soft_gain_set(xcfg_cb.mic_soft_gain);

}
AT(.com_text.wireless_mic_mix_aux)
void mic_mix_aux_input(u8 *ptr, u32 samples, int ch_mode, void *params)
{
    s16 *rptr = (s16 *)ptr;
    s32 temp_mix = 0;
    if(ch_mode == 2){
        for(int i = 0;i < samples;i++){
            temp_mix = rptr[i*2+1] + rptr[i*2]; //左右通道MIX 后转换成单声道数据推进编码流程
            if(temp_mix > 32767) {
                rptr[i]  = 32767;
            } else if(temp_mix < -32767){
                rptr[i]  = -32767;
            } else {
                rptr[i]  = temp_mix;
            }
        }
        ch_mode = 1;
    }
    mic_mix_aux_output_callback(ptr,samples,ch_mode,NULL);
}

AT(.text.bsp.wireless_mic_mix_aux)
void mic_mix_aux_audio_output_callback_set(audio_callback_t callback)
{
    mic_mix_auxcfg.callback        = mic_mix_aux_input;    //adc 中断回调用函数
    mic_mix_aux_output_callback    = callback;             //下一级模块 回掉函数
}

AT(.text.bsp.wireless_mic_mix_aux)
void mic_mix_aux_start(void)
{
    sdadc_init(&mic_mix_auxcfg);
    sdadc_start(mic_mix_auxcfg.channel);

    /// DC 去直流 关闭高通滤波器 恢复一些低频信号
    #if DEVICE_MIC_DC_EN
    #define SDADCDIGCON     SFR_RW (SFR1_BASE + 0x37*4)
    SDADCDIGCON &= ~(BIT(29) | BIT(30));
    SDADCDIGCON |= BIT(22) | BIT(23);
    SDADCDIGCON |= (BIT(1) | BIT(9));
    #endif

    sdadc_w4_kick = true;
}

AT(.com_text.bsp.wireless_mic_mix_aux)
void wireless_mic_mix_aux_kick(void)
{
    if (sdadc_w4_kick) {
        sdadc_w4_kick = false;
        sdadc_start_kick(mic_mix_auxcfg.channel);
    }
}

AT(.text.bsp.wireless_mic_mix_aux)
void mic_mix_aux_stop(void)
{
    sdadc_exit(mic_mix_auxcfg.channel);
}

#endif
